/**
 * 防抖Hook
 */

import { ref, unref } from 'vue'

export function useDebounce(fn, delay = 300) {
  let timeoutId = null
  
  const debouncedFn = (...args) => {
    return new Promise((resolve, reject) => {
      // 清除之前的定时器
      if (timeoutId) {
        clearTimeout(timeoutId)
      }
      
      // 设置新的定时器
      timeoutId = setTimeout(async () => {
        try {
          const result = await fn(...args)
          resolve(result)
        } catch (error) {
          reject(error)
        }
      }, delay)
    })
  }
  
  // 取消防抖
  debouncedFn.cancel = () => {
    if (timeoutId) {
      clearTimeout(timeoutId)
      timeoutId = null
    }
  }
  
  return debouncedFn
}

export function useThrottle(fn, delay = 300) {
  let lastCallTime = 0
  
  return (...args) => {
    const now = Date.now()
    
    if (now - lastCallTime >= delay) {
      lastCallTime = now
      return fn(...args)
    }
  }
}

export default useDebounce
